package com.infinite.controller;

import com.infinite.mapper.DepartmentMapper;
import com.infinite.mapper.EmployeeMapper;
import com.infinite.pojo.Department;
import com.infinite.pojo.Employee;
import com.infinite.service.EmployeeService;
import com.infinite.vo.EmployeeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;
import java.util.List;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    DepartmentMapper departmentMapper;
    //获得所有的员工信息
    @RequestMapping("emps")
    public String list(Model model){
        List<EmployeeVo> allEmployee = employeeService.getAllEmployee();
        model.addAttribute("emps",allEmployee);
        return "emps/list";
    }

    @GetMapping("emp")
    public String toAddPage(Model model){
        Collection<Department> departments = departmentMapper.getDepartments();
        model.addAttribute("departments",departments);
        return "emps/add";
    }
    @PostMapping("emp")
    public String addEmployee(Employee employee){
        employeeMapper.add(employee);
        return "redirect:/emps";
    }
    @GetMapping("emp/{id}")
    public String toUpdatePage(@PathVariable("id") Integer id,Model model){
        Employee employeeById = employeeMapper.getEmployeeById(id);
        Collection<Department> departments = departmentMapper.getDepartments();
        model.addAttribute("emp",employeeById);
        model.addAttribute("departments",departments);
        return "emps/update";
    }
    @PostMapping("updateEmp")
    public String update(Employee employee,Model model){
        employeeMapper.update(employee);
        return "redirect:/emps";
    }
    @RequestMapping("delete/{id}")
    public String delete(@PathVariable("id") Integer id,Model model){
        employeeMapper.deleteEmployeeById(id);
        return "redirect:/emps";

    }
}
